/*
Majority of code taken from AutoIT

Copyright 2006 Jonathon Bennett and the AutoIT Authors

http://www.autoitscript.com/autoit3/docs/credits.htm

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h"
#include "Utility.h"


///////////////////////////////////////////////////////////////////////////////
// Util_RegReadString()
//
// Read a string from a registry key
//
///////////////////////////////////////////////////////////////////////////////

void Util_RegReadString(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, DWORD dwBufLen, char *szValue )
{
	HKEY	hRegKey;

	// Make sure the return value is blank just in case we error
	szValue[0] = '\0';

	if (RegOpenKeyEx(hKey, lpSubKey, 0, KEY_QUERY_VALUE, &hRegKey) != ERROR_SUCCESS)
		return;

	RegQueryValueEx(hRegKey, lpValueName, NULL, NULL, (LPBYTE)szValue, &dwBufLen);

	RegCloseKey(hRegKey);

} // Util_RegReadString()





///////////////////////////////////////////////////////////////////////////////
// Util_StripTrailingDir()
//
// Makes sure a filename does not have a trailing //
//
///////////////////////////////////////////////////////////////////////////////

void Util_StripTrailingDir(char *szPath)
{
	int len = (int)strlen(szPath)-1;

	if (szPath[len] == '\\')
		szPath[len] = '\0';

} // Util_StripTrailingDir




///////////////////////////////////////////////////////////////////////////////
// Util_GetIPAddress()
//
// Gets an IP address for adapter nn (1 is first)
//
// szInetBuf must be at least 16 chars long
//
///////////////////////////////////////////////////////////////////////////////

void Util_GetIPAddress(int nAdapter, char *szInetBuf)
{
	HOSTENT		*lpHost;
	IN_ADDR		inaddr;
	WSADATA		wsadata;
	char		szBuf[256];
	int			nNumAdapters;

	if( WSAStartup(MAKEWORD(1, 1), &wsadata) == 0 )
	{
		gethostname(szBuf, sizeof(szBuf) );
		lpHost = gethostbyname(szBuf);

		// How many adapters have we?
		nNumAdapters = 0;
		while(lpHost->h_addr_list[nNumAdapters] != NULL)
			nNumAdapters++;

		if (nAdapter > nNumAdapters)
			strcpy(szInetBuf, "0.0.0.0");
		else
		{
			memcpy(&inaddr,lpHost->h_addr_list[nAdapter-1], 4);
			strcpy(szInetBuf, (char*)inet_ntoa(inaddr));
		}

		WSACleanup();

	}

} // Util_GetIPAddress()
